// pages/index/reduce/index.js
const tools = require('../../../utils/tool')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    schedule: false,
    showShare: false,
    newHtml: '', //富文本内容
    options: [{
        name: '微信好友',
        icon: 'wechat',
        openType: 'share'
      },
      {
        name: '微信朋友圈',
        icon: 'wechat-moments'
      },
    ],
    show: false,
    isZan: false,
    collect: false,
    isPlay: true,
    swiperList: [],
    Detail: {},
    id: 0,
    batchDate: '', //创建时间
    reportContent: '', //举报内容
    isShare:0,  //如果分享页进来1 否则是0
  },
  onClose() {
    this.setData({
      show: false
    });
  },

  onSelect(event) {
    this.setData({
      show: false,
      reportContent: event.detail.name
    });
    this.getReport()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    options.praised =options.praised=='true'?true:false
    options.collected =options.collected=='true'?true:false
    this.load()
    this.setData({
      parameter: options,
      isShare:options.isShare
    })
    this.getDetail(options.id, '/aty/applet/a/article/')
  },
  load() {
    // 微信、QQ、百度
    var ctx = this.selectComponent('#article')
    var text = ctx.getText()
    this.setData({
      newHtml: text,
    })
  },
  showPopup() {
    this.setData({
      show: true
    });
  },

  // 获取文章详情
  getDetail(id, url) {
    tools.showLoading()
    let detail = tools.request(url + id, 'get', {})
    detail.then(res => {
      console.log(res)
        wx.hideLoading()
        if (res.statusCode==200) {
          if(res.data.content.indexOf('img')!=-1){ //判断img是否存在
            var result = res.data.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match,capture) {
            return '<img src='  +   encodeURI(capture.replaceAll('\\', '/'))+'/>';
                  });
                   
          }else{
            var result=res.data.content
          }
        var imgList= this.getImgSrc(res.data.content) //提取富文本中图片下载

          this.setData({
            Detail: res.data,
            content:result,
            imgList
          })
        } else {
          tools.showToast(res.data.error_msg, 'error')
        }
      })
      .catch(err => {
        tools.showToast(err.errMsg, 'error')
      })
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  getImgSrc(richtext) {
    let imgList = [];
    richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
          imgList.push(capture);
    });
    return imgList;
},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 收藏文章
  bindCollect() {
    tools.showLoading()
    // 点赞还是取消点赞
    let methods=this.data.parameter.collected?'delete':'post'
    console.log(methods)
    let Collect = tools.request('/aty/applet/a/collect/' + this.data.Detail.id, methods, {}, wx.getStorageSync('token'))
    Collect.then(res => {
      console.log(res)
        wx.hideLoading()
        if (res.statusCode==200 || res.statusCode==204) {
          if (this.data.parameter.collected) {
            this.setData({
              [`parameter.collected`]: !this.data.parameter.collected,
              [`Detail.collectNum`]: this.data.Detail.collectNum - 1
            })
            tools.showToast('取消收藏')
          } else {
            this.setData({
              [`parameter.collected`]: !this.data.parameter.collected,
              [`Detail.collectNum`]: this.data.Detail.collectNum + 1
            })
            tools.showToast('收藏成功')
          }
          this.setData({
            collect: !this.data.collect
          })
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
          prevPage.setData({
            mydata: {
              id: this.data.parameter.id,
              collected: this.data.parameter.collected,
              collect_num: this.data.parameter.collectNum,
              collect: this.data.collect
            }
          })
        } else {
          tools.showToast(res.data.error_msg, 'error')
        }
      })
      .catch(err => {
        tools.showToast(err.errMsg, 'error')
      })
  },
  // 点赞
  bindGive(e) {
    // tools.showLoading()
    console.log(e.currentTarget.dataset.id)

    let id = e.currentTarget.dataset.id
    console.log(this.data.parameter.praised)
    let methods=this.data.parameter.praised?'DELETE':'post'
    console.log(methods)
    let give = tools.request('/aty/applet/a/praise/' + id, methods, {},wx.getStorageSync('token'))
    give.then(res => {
      // wx.hideLoading()
      if (res.statusCode==200 || res.statusCode==204) {
        console.log(res)
        if (this.data.parameter.praised) {
          this.setData({
            [`parameter.praised`]: !this.data.parameter.praised,
            [`Detail.clickNum`]: this.data.Detail.clickNum - 1
          })
          tools.showToast('取消点赞')
        } else {
          this.setData({
            [`parameter.praised`]: !this.data.parameter.praised,
            [`Detail.clickNum`]: this.data.Detail.clickNum + 1
          })
          tools.showToast('点赞成功')
        }
        this.setData({
          isZan: !this.data.isZan
        })
        console.log(this.data.parameter.id,this.data.parameter.praised)
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面z
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
        prevPage.setData({
          mydata: {
            id: this.data.parameter.id,
            praised: this.data.parameter.praised,
            // ZanCount: this.data.Detail.click_num,
            isZan: this.data.isZan
          }
        })
      
      } else {
        tools.showToast(res.data.error_msg, 'error')
      }
    })
  },
  
 
  //分享
  onShareAppMessage: function () {
    console.log(this.data.Detail,1122)
//     collected: false
// id: "46"
// index: "1"
// praised: true
    let shareData = this.data.Detail
    let that = this
    let id = shareData.id
    let imgurl = shareData.cover
    // let share = tools.request('/api/applets/article/share/' + id, 'get', {},wx.getStorageSync('token'))
    // share.then(res => {
    //   if (res.data.status) {
    //     this.setData({
    //       [`Detail.share_num`]: that.data.Detail.share_num + 1
    //     })
    //   }
    // })
    return {
      title: shareData.title,
      path: `/pages/index/reduce/index?id=${id}&isShare=1`,
      imageUrl: imgurl
    }
  },
  // 关注
  bindAttention(e) {
    tools.showLoading()
    let author_id = e.currentTarget.dataset.author_id
    let index = e.currentTarget.dataset.index
    let attention = tools.request('/api/applets/follow/add', 'post', {
      user_id: author_id
    }, wx.getStorageSync('token'))
    attention.then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.data.status) {
        console.log(this.data.Detail.is_follow)
        this.setData({
          [`Detail.is_follow`]: !this.data.Detail.is_follow
        })

        if (this.data.Detail.is_follow) {
          tools.showToast('关注成功')
        } else {
          tools.showToast('取消成功')
        }
      }
    })
  },

  // 图片预览
  ViewImage(e) {
    let urls = []
    this.data.swiperList.forEach(e => {
      urls.push(e.path)
    })
    wx.previewImage({
      urls: urls,
      current: e.currentTarget.dataset.url
    });
  },
 
  goLabelDetail(e) {
    let Detail = this.data.Detail
    wx.navigateTo({
      url: `../labelDetail/labelDetail?name=${e.currentTarget.dataset.name}&author=${Detail.author}&headimg=${Detail.headimg}`,
    })
  },
  onShow() {
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1] // 当前页
    console.log()
    if (currPage.data.isBack) {
      //如果是从上个页面传的值则赋值remarks  1
      this.setData({
        [`Detail.is_follow`]: currPage.data.is_follow
      })
    }
  },

  onClick(event) {

    this.setData({
      showShare: true,
    });
  },

  onCloseShare() {
    this.setData({
      showShare: false
    });
  },
  // 选择分享朋友或朋友圈
  onSelectShare(event) {
    let that = this
    if (event.detail.name == '微信朋友圈') {
      // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
      wx.getSetting({
        success(res) {
          console.log("getSetting: success");
          if (!res.authSetting['scope.writePhotosAlbum']) {
            // 接口调用询问  
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                that.upLoad()
              },
              fail() {
                // 用户拒绝了授权  
                wx.showModal({
                  title: '保存图片',
                  content: '保存图片需要您授权',
                  showCancel: true,
                  confirmText: '确定',
                  success: function (res) {
                    if (res.confirm) {
                      // 打开设置页面  
                      wx.openSetting({
                        success: function (data) {
                          if (data.authSetting['scope.writePhotosAlbum']) {
                            that.upLoad()
                          } else {
                            console.log("授权失败");
                          }
                        },
                        fail: function (data) {
                          console.log("openSetting: fail");
                        }
                      });
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }

                  }
                })
              }
            })
          } else {
            that.upLoad()
          }
        }
      })
    }
    this.onCloseShare();
  },

  upLoad() {
    let imgList = this.data.imgList
    this.getsave(0, imgList.length, imgList)
  },


  getsave(i, length, newList) {
    console.log(newList)
   let that=this
    wx.showLoading({
      title: '下载中(' + (i + 1) + '/' + length + ')'
    })
    const downloadTask = wx.downloadFile({
      url: newList[i],
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            if (i + 1 == length) {
              wx.showToast({
                title: '保存成功',
              });
              wx.setClipboardData({
                data: this.data.newHtml,
                success(res) {
                  wx.showToast({
                    title: '图片已下载,内容已复制',
                    icon: 'none'
                  })
                  let share = tools.request('/api/applets/article/share/' + that.data.Detail.id, 'get', {},wx.getStorageSync('token'))
                  share.then(res => {
                  })
                }
              })
            }
            if (++i < length) {
              this.getsave(i, length, newList);
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '保存图片失败',
              icon: 'none',
            })
          },
        })
      },
    })
  },
  // 下载视频
  getsaveVideo(video_url) {
    let that=this
    const downloadTask = wx.downloadFile({
      url: video_url,
      success: (res) => {
        wx.saveVideoToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            wx.setClipboardData({
              data: this.data.newHtml,
              success(res) {
                wx.showToast({
                  title: '视频已下载,内容已复制',
                  icon: 'none'
                })
                var share= tools.request('/api/applets/article/share/' + that.data.Detail.id, 'get', {},wx.getStorageSync('token'))
                share.then(res => {
                })
              }
            })
          },
          fail: (err) => {
            wx.showToast({
              title: '保存失败',
              icon: 'none',
            })
          },
        })
      },
    })
    // 下载进度
    downloadTask.onProgressUpdate((res) => {
      if (res.progress > 0) {
        this.setData({
          schedule: true,
          percent: res.progress
        })
      }
      if (res.progress == 100) {
        this.setData({
          schedule: false
        })
      }
    })
  },
  saveImageToPhotos(filePath) {
    let self = this
    // 相册授权
    wx.getSetting({
      success(res) {
        console.log(res)
        // 进行授权检测，未授权则进行弹层授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              self.saveImage(filePath)
            },
            // 拒绝授权时，则进入手机设置页面，可进行授权设置
            fail() {
              wx.openSetting({
                success: function (data) {
                  console.log("openSetting success");
                },
                fail: function (data) {
                  console.log("openSetting fail");
                }
              });
            }
          })
        } else {
          // 已授权则直接进行保存图片
          self.saveImage(filePath)
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
 
})